//
//  RxGestureExample.swift
//  SwiftCode
//
//  Created by 于虎拴 on 2022/11/18.
//

import Foundation
import UIKit
import RxSwift
import RxGesture

final class RxGestureExample: ListViewController {
  override func getItemCount() -> Int {
    data.count
  }
  
  override func getItem(_ indexPath: IndexPath) -> Item {
    data[indexPath.row]
  }
  
  private lazy var data: [Item] = [
    .init(title: "UITapGestureRecognizer", description: "点击手势，需要点击2次", action: { [weak self] in self?.tapGesture() }),
    .init(title: "UILongPressGestureRecognizer", description: "长按手势", action: { [weak self] in self?.longPressGesture() }),
    .init(title: "UIPanGestureRecognizer", description: "平移手势，实现拖动 UIView", action: { [weak self] in self?.pinGesture() })
  ]
  
  private let bag = DisposeBag()
  
  /// 点击手势
  private func tapGesture() {
    targetView.rx.tapGesture() { gesture, _ in
      gesture.numberOfTapsRequired = 2 // 省略闭包时为1
    }
    .when(.recognized)
    .subscribe(onNext: { [weak self] _ in
      self?.targetView.backgroundColor = getColor()
    })
    .disposed(by: bag)
  }
  
  /// 长按手势
  private func longPressGesture() {
    targetView.rx.longPressGesture()
      .when(.began)
      .subscribe(onNext: { [weak self] _ in
        self?.targetView.backgroundColor = getColor()
      })
      .disposed(by: bag)
  }
  
  private var lastTransform = CGAffineTransform(translationX: 0.0, y: 0.0)
  /// 平移手势，实现拖动 UIView
  private func pinGesture() {
    let panGesture = targetView.rx
      .panGesture()
      .share(replay: 1)
    
    panGesture
      .when(.possible, .began, .changed)
      .asTranslation()
      .subscribe(onNext: { [weak self] translation, _ in
        guard let self else { return }
        self.targetView.transform = self.lastTransform.translatedBy(x: translation.x, y: translation.y)
      })
      .disposed(by: bag)
    
    panGesture
      .when(.ended)
      .asTranslation()
      .subscribe(onNext: { [weak self] translation, velocity in
        guard let self else { return }
        // 上👆🏻 t.y < 0, v.x < 0
        // 下👇🏻 t.y > 0, v.x > 0
        // 左👈🏻 t.x < 0, v.x < 0
        // 右👉🏻 t.x < 0, v.x < 0
        debugPrint("translation", translation)
        debugPrint("velocity", velocity)
//        self.lastTransform = self.targetView.transform
      })
      .disposed(by: bag)
  }
  
  override func viewDidLoad() {
    super.viewDidLoad()
    
    view.addSubview(targetView)
    targetView.snp.makeConstraints { make in
      make.size.equalTo(100)
      make.center.equalToSuperview()
    }
  }
  
  private lazy var targetView: UIView = {
    let view = UIView()
    view.backgroundColor = getColor()
    view.layer.cornerRadius = 8
    view.layer.masksToBounds = true
    return view
  }()
}

private let colors: [UIColor] = [.red, .orange, .yellow, .green, .blue, .cyan, .purple]
private var index = -1
private func getColor() -> UIColor {
  index += 1
  return colors[index % colors.count]
}
